package com.lee.redisplus.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * @author jackielee
 * @version 1.0
 * @description RedisConfig
 * @date 2021/4/9
 **/
@EnableCaching
@Configuration
public class RedisConfig {

    /**
     * 修改序列方式
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(Object.class);

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); // 过时，则通过其内调用的方法使用以下代码
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);

        serializer.setObjectMapper(objectMapper);

        template.setKeySerializer(new StringRedisSerializer()); // 字符串key类型
        template.setValueSerializer(serializer);

        template.setHashKeySerializer(new StringRedisSerializer()); // hash key类型
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet();
        return template;
    }

    /**
     * redis缓存管理器
     * @param template
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate<String, Object> template){
        // redis缓存管理器
        RedisCacheManager redisCacheManager = RedisCacheManager.RedisCacheManagerBuilder
                .fromConnectionFactory(template.getConnectionFactory())
                .cacheDefaults(getCacheConfigurationWithTtl(template, 60 * 60))
                .withCacheConfiguration("cache_user", getCacheConfigurationWithTtl(template, 10))
                .transactionAware() // 配置同步修改或删除 put/evict
                .build();
        return redisCacheManager;
    }

    private RedisCacheConfiguration getCacheConfigurationWithTtl(RedisTemplate<String, Object> template, int seconds) {
        return RedisCacheConfiguration
                .defaultCacheConfig()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(template.getStringSerializer()))// 设置key为String
        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(template.getValueSerializer())) // 设置value为json的object
        .disableCachingNullValues() // 不缓存null
        .entryTtl(Duration.ofSeconds(seconds)); // 缓存保存seconds秒
    }
}
